 /*
    *  Copyright 2004 Thevert Liu  <thevert.liu@gmail.com>
    *
    *  Licensed under the Apache License, Version 2.0 (the "License");
    *  you may not use this file except in compliance with the License.
    *  You may obtain a copy of the License at
    *
    *      http://www.apache.org/licenses/LICENSE-2.0
    *
   *  Unless required by applicable law or agreed to in writing, software
  *  distributed under the License is distributed on an "AS IS" BASIS,
   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   *  See the License for the specific language governing permissions and
   *  limitations under the License.
   */
#ifndef X2_TYPETRANS_H
#define X2_TYPETRANS_H

#include <string>
#include <sstream>

template<class T>
class TypeTrans
{
public:
    static bool S2V(const std::string& s,  T& t) {
        std::stringstream ss(s) ;
        if (!(ss>>t)) {
            return false ;
        }
        return true ;
    }
    
    static bool V2S(const T& t, std::string& s) {
        std::stringstream ss;
        ss << t ;
        s = ss.str();
        return !s.empty() ;
    }
} ;

template<> class TypeTrans<bool>
{
public:
       
    static bool S2V(const std::string& s, bool& t) {
         if (s=="true") {
             t = true ;
         } else if (s=="false") {
             t = false ;
         } else {
             return false;
         }
         return true ;
    }
    
    static bool V2S(bool& t, std::string& s) {
         if (t) {
            s = "true" ;
         } else {
            s = "false" ;
         }
         return true ;
    }
} ;

struct Millisec
{
	time_t seconds ;
} ;

template<> class TypeTrans<Millisec>
{
    static bool S2V(const std::string& s, Millisec& t) {
		if (s=="0") {
			t.seconds = 0 ;
		} else if (s.length()<=3){
		    t.seconds = 1 ;
		} else {
		    std::stringstream ss(s.substr(0, s.length()-3)) ;
			return (ss >> t.seconds) ;
		}
        return true ;
    }
    
    static bool V2S(Millisec& t, std::string& s) {
		std::stringstream ss ;
		ss << t.seconds << "000" ;
		s = ss.str() ;
        return true ;
    }
} ;


#endif //X2_TYPETRANS_H



